#pragma once
#include <iostream>
#include <unistd.h>
#include <fcntl.h>
#include <string>
#include <vector>

// 非阻塞设置
void SetNonBlock(int sock)
{
  int f = fcntl(sock, F_GETFL);
  if (f < 0)
  {
    std::cerr << "fcntl errror" << std::endl;
    return;
  }
  fcntl(sock, F_SETFL, f | O_NONBLOCK);
}

// 1+2 H 33+4 H 3+5
void SplitSegment(std::string &inbuffer, std::vector<std::string> *tokens, std::string sep)
{
  while (true)
  {
    std::cout<<"inbuffer"<<inbuffer<<std::endl;
    auto pos = inbuffer.find(sep);
    if (pos == std::string::npos)
    {
      break;
    }
    std::string sub = inbuffer.substr(0, pos);
    tokens->push_back(sub);              // 截取 1+2 到tokens中
    inbuffer.erase(0, pos + sep.size()); // 例如去掉 1+2 H
  }
}

// 反序列化--提取有效参与计算或者存储信息
// 1+2
bool Deserialize(const std::string &segment, std::string *out1, std::string *out2)
{
  std::string op = "+";
  auto pos = segment.find(op);
  if (pos == std::string::npos)
    return false;
  *out1 = segment.substr(0, pos);          // 1
  *out2 = segment.substr(pos + op.size()); // 2
  return true;
}
